package com.infocollect.project.api.ui;


import com.infocollect.project.api.entity.TappProcessEntity;
import com.infocollect.project.api.helper.CurrentHelp;
import com.infocollect.project.api.helper.MapHelper;
import com.infocollect.project.api.req.LoadProcessFromInfoReq;
import com.infocollect.project.api.service.ITappPorcessinsService;
import com.infocollect.project.api.service.ITappProcessService;
import com.infocollect.project.api.vo.CurrentUserInfoVO;
import com.infocollect.project.form.vo.R;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j2;
import net.sf.json.JSONObject;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * (TappProcess)表控制层
 *
 * @author makejava
 * @since 2019-12-25 10:32:30
 */
@Log4j2
@Api(value = "Process", tags = "流程模板信息")
@RestController
@RequestMapping("Process")
public class TappProcessController {
    /**
     * 服务对象
     */
    @Resource
    private ITappProcessService tappProcessService;

    /**
     * 服务对象
     */
    @Resource
    private ITappPorcessinsService tappPorcessinsService;
    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("selectOne")
    public R<TappProcessEntity> selectOne(Long id) {
        return R.newOk( this.tappProcessService.queryById(id));
    }

    /**
     * 查询流程列表
     *
     * @param param post过来的参数
     * @return 单条数据
     */
    @PostMapping("queryProcess")
    public R<List<TappProcessEntity>> queryPageList(@RequestBody Map<String, String> param) throws Exception {
        TappProcessEntity user = new TappProcessEntity();
        MapHelper.setObjectValue(user, param);
        int page = Integer.parseInt(param.get("page"));
        int rows = Integer.parseInt(param.get("rows"));
        PageHelper.startPage(page, rows);
        Boolean IsAll=!(param.get("fversion")==null||param.get("fversion").length()==0);
        List<TappProcessEntity> list = this.tappProcessService.QueryList(user,IsAll);
        PageInfo pageInfo = new PageInfo(list);
        return R.newOk(list,(int)pageInfo.getTotal());

    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @PostMapping("del/{id}")
    @ResponseBody
    public R<String> Delete(@PathVariable(name = "id") Long id) throws IOException {
       if (this.tappProcessService.deleteById(id)) {
            return R.newOk("操作成功！");
        } else {
            return R.newError("操作失败！");
        }

    }

    /**
     * 保存流程数据
     *
     * @param param
     * @return
     * @throws IOException
     */
    @PostMapping("SaveFlowData")
    @ResponseBody
    public R<Object> SaveFlowData(@RequestBody Map<String, String> param) throws IOException {
        Object returnObj= tappProcessService.SaveFlowData(param,null);
        return R.newOk( returnObj);
    }

    /**
     * 设计时 启动流程
     * @param param
     * @return
     * @throws IOException
     */
    @PostMapping("DesignStartFlow")
    @ResponseBody
    public R<Object> DesignStartFlow(@RequestBody Map<String, String> param) throws IOException{
        Object returnObj= tappProcessService.SaveFlowData(param,2);
        return R.newOk( returnObj);
    }
    /**
     * 停止流程模板
     *
     * @param
     * @return
     * @throws IOException
     */
    @PostMapping("StopFlow/{processid}")
    public  R<Long> StopFlow(@PathVariable(name = "processid") Long processid) throws  Exception{
        Long processID = tappProcessService.StopFlow(processid);
        return R.newOk( processID);

    }
    /**
     * 启动流程模板
     *
     * @param
     * @return
     * @throws IOException
     */
    @PostMapping("StartFlow/{processid}")
    public  R<Long> GridStartFlow(@PathVariable(name = "processid") Long processid)throws  Exception{
        Long processID = tappProcessService.StartFlow(processid);
        return R.newOk(processID);
    }
    /**
     * 保存流程数据
     *
     * @param
     * @return
     * @throws IOException
     */
    @PostMapping("StartFlow")
    @ResponseBody
    public  R<Object> StartFlow(@RequestBody Map<String, String> param) throws IOException{
        Object returnObj= tappProcessService.SaveFlowData(param,2);
        return R.newOk(returnObj);

    }
    /**
     * 保存流程数据
     *
     * @param
     * @return
     * @throws IOException
     */
    @PostMapping("SaveAsFlow")
    @ResponseBody
    public  R<String> SaveAsFlow(@RequestBody Map<String, String> param)throws Exception{
        if(param.get("processid")==null||param.get("processid").length()==0){
            return R.newError("传入参数有误！");
        }
        if(param.get("processname")==null||param.get("processname").length()==0){
            return R.newError("传入参数有误！");
        }
        if(param.get("processcode")==null||param.get("processcode").length()==0){
            return  R.newError("传入参数有误！");
        }
        Long processid=Long.parseLong(param.get("processid"));
        tappProcessService.SaveAsFlow(processid,param.get("processname"),param.get("processcode"));
       return R.newOk("保存成功！");
    }
    /**
     * 保存流程数据
     *
     * @param
     * @return
     * @throws IOException
     */
    @PostMapping("CheackProcesscode/{Code}")
    @ResponseBody
    public R<String> CheackProcesscode(@PathVariable(name = "Code") String Code)throws IOException{
      if(!tappProcessService.CheackProcesscode(Code)){
          return    R.newError("流程编码已存在！");
      }
        return R.newOk("输入验证码正确！");
    }

    @ApiOperation("加载流程表单 流程基本信息")
    @PostMapping ("/loadProcessFromInfo")
    @ResponseBody
    public R<JSONObject> loadProcessFromInfo(@RequestBody LoadProcessFromInfoReq param) throws IOException {
        try {
            CurrentUserInfoVO currentUserInfo = CurrentHelp.Ins.GetUser();
            JSONObject result = new JSONObject();
            JSONObject model = new JSONObject();
            model.put("userfid", currentUserInfo.getUserId().toString());// AuthIdentity.USERFID;
            model.put("userno", currentUserInfo.getUserName());// AuthIdentity.UserName;
            model.put("username", currentUserInfo.getRealaname()); // ViewBag.USERNAME = "ds";// AuthIdentity.RealaName;
            model.put("deptid", currentUserInfo.getDeptid().toString());     //ViewBag.DEPTID = "ds";//AuthIdentity.DEPTID;
            model.put("deptname", currentUserInfo.getDeptname());  /// ViewBag.DEPTNAME = "ds";//AuthIdentity.DEPTNAME;
            model.put("organid", currentUserInfo.getOrganid().toString());     //ViewBag.DEPTID = "ds";//AuthIdentity.DEPTID;
            model.put("organname", currentUserInfo.getOrganname());
            model.put("organcode", currentUserInfo.getOrgancode());     //ViewBag.DEPTID = "ds";//AuthIdentity.DEPTID;
            model.put("deptcode", currentUserInfo.getDeptcode());
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String dateString = formatter.format(new Date());
            model.put("datetime", dateString);   //ViewBag.DateTime = DateTime.Now;
            model.put("encryptstring", "ds");   //ViewBag.EncryptString = "ds";// DESEncrypt.DesEncrypt(AuthIdentity.UserName);。
            result.put("currentUserInfo",model);
            result.put("Process", tappPorcessinsService.GetProcessFromInfo(param.getProcessid(),param.getProcessinsid(),param.getActinsid(), currentUserInfo.getUserName(), param.getViewmodel()));
            return R.newOk(result);
        }catch (Exception ex){
            log.error("获取流程基本信息失败，具体错误信息："+ex.toString());
            System.out.println("获取流程基本信息失败，具体错误信息："+ex.toString());
            return R.newError("获取流程基本信息失败，具体错误信息："+ex.toString());
        }
    }
}